#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import conf
import paper
import utils
import papernavbar
import xnuser
import permission

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        xnuidInt = 0
        if is_logged_in:
            try:
                xnuidInt = int(cookieDict.get('user'))
            except ValueError:
                xnuidInt = 0
            xnuser.getAndUpdateUserData(xnuidInt, cookieDict.get('session_key'))
        nav = self.request.get('nav')
        category = utils.getCategoryByNav(nav)
        errMsg = ''
        paperNavbar = papernavbar.getPaperNavbar(self.request)        
        paperList = []
        if not errMsg:
            if not category or category == 'all':
                paperList = paper.listAllPapers(paperNavbar['offset'], paperNavbar['limit'])
            else:
                paperList = paper.listPapersByCategory(category, paperNavbar['offset'], paperNavbar['limit'])
        
        authorIdList = []
        for paperModel in paperList:
            if paperModel.authorId not in authorIdList:
                authorIdList.append(paperModel.authorId)
        xnUserModelList = xnuser.getXnUserByIds(authorIdList)
        #construct a (xnuid->name) map
        xnuid2name = {}
        for xnUserModel in xnUserModelList:
            if xnUserModel.xnuid not in xnuid2name:
                xnuid2name[xnUserModel.xnuid] = xnUserModel.name
        
        #attach a user name with each paper model
        for paperModel in paperList:
            if paperModel.authorId in xnuid2name:
                paperModel.authorName = xnuid2name[paperModel.authorId]
            else:
                paperModel.authorName = str(paperModel.authorId)
            paperModel.catText = utils.getCategoryTextByValue(paperModel.category)
        
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'api_key':conf.api_key,
            'isLoggedIn': is_logged_in,
            'nav_bar_title': '最新文章列表',
            'navRssLink': '订阅本站文章',
            'paperCategoryList': conf.paperCategoryList,
            'sysPaperUrlCelebrating': conf.sysPaperUrlCelebrating,
            'sysPaperUrlFaq': conf.sysPaperUrlFaq,
            'sysPaperUrlSiteEvents': conf.sysPaperUrlSiteEvents,
            'sysPaperUrlHowToRss': conf.sysPaperUrlHowToRss,
            'paperList': paperList,
            'paperNavbar': paperNavbar,
            'nav_selected': nav,
            'isAdministrator': permission.isAdministrator(xnuidInt)
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/index.html')
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/.*', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

